//	@title			磁盘监控系统API
//	@version		1.0.0
//	@description	一个现代化的磁盘性能监控工具，提供实时监控、历史数据分析和可视化展示
//	@termsOfService	https://gitee.com/liumou_site/disk-monitoring

//	@contact.name	liumou_site
//	@contact.url		https://gitee.com/liumou_site/disk-monitoring
//	@contact.email	liumou_site@163.com

//	@license.name	MIT
//	@license.url		https://gitee.com/liumou_site/disk-monitoring/blob/master/LICENSE

//	@host		localhost:8080
//	@BasePath	/

package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"gitee.com/liumou_site/disk-monitoring/backend/configs"
	_ "gitee.com/liumou_site/disk-monitoring/backend/docs"
	"gitee.com/liumou_site/disk-monitoring/backend/info"
	"gitee.com/liumou_site/disk-monitoring/backend/internal/api"
	"gitee.com/liumou_site/disk-monitoring/backend/internal/service"
	"gitee.com/liumou_site/disk-monitoring/backend/route"
	"gitee.com/liumou_site/disk-monitoring/backend/web"
	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

//	@securityDefinitions.basic BasicAuth

func main() {
	// 命令行参数
	var (
		host       = flag.String("host", "0.0.0.0", "监听地址")
		port       = flag.Int("port", 8080, "监听端口")
		version    = flag.Bool("version", false, "显示版本信息")
		help       = flag.Bool("help", false, "显示帮助信息")
		serviceCmd = flag.String("service", "", "服务管理命令: install, uninstall, update")
		logFile    = flag.String("log", "", "指定日志文件路径")
	)
	flag.Parse()

	// 创建服务管理器
	serviceManager := configs.NewServiceManager()

	// 服务管理命令
	if *serviceCmd != "" {
		serviceManager.HandleServiceCommand(*serviceCmd)
		return
	}

	// 检查是否在服务模式下运行
	if configs.IsService() {
		if err := serviceManager.RunAsService(); err != nil {
			log.Fatal("服务运行失败: ", err)
		}
		return
	}

	// 显示版本信息
	if *version {
		info.ShowVersion()
		return
	}

	// 显示帮助信息
	if *help {
		info.ShowHelp()
		return
	}

	// 打印启动信息
	info.ShowStartupInfo()

	// 创建服务实例
	diskService := service.NewDiskService()
	processService := service.NewProcessService()

	// 创建处理层实例
	diskHandler := api.NewDiskHandler(diskService)
	processHandler := api.NewProcessHandler(processService)

	// 创建gin引擎
	r := gin.Default()

	// 设置API路由
	route.SetupRoutes(r, diskHandler, processHandler)

	// 注册swagger路由
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

	// 设置前端静态文件路由（embed嵌入）
	staticFS := web.GetFileSystem()
	r.NoRoute(func(c *gin.Context) {
		web.SPAHandler(staticFS)(c.Writer, c.Request)
	})

	// 使用命令行参数配置
	listenAddr := fmt.Sprintf("%s:%d", *host, *port)

	// 设置日志文件
	if *logFile != "" {
		logFile, err := os.OpenFile(*logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
		if err != nil {
			log.Printf("无法打开日志文件，使用标准输出: %v", err)
		} else {
			log.SetOutput(logFile)
		}
	}

	// 启动服务器
	log.Printf("服务器启动，监听地址: %s", listenAddr)
	log.Printf("访问地址: http://%s", listenAddr)
	log.Printf("API文档: http://%s/swagger/index.html", listenAddr)

	if err := r.Run(listenAddr); err != nil {
		log.Fatal("服务器启动失败: ", err)
	}
}
